package Work;

import Work.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ProductService {
    private final Map<String, Product> productData = new HashMap<>();
    private String dataFilePath; // 从配置文件读取的路径

    public ProductService() {
        loadConfig(); // 先加载配置
        loadData();   // 再加载数据
    }

    // 加载配置文件
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStreamReader isr = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(isr);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
        } catch (FileNotFoundException e) {
            System.out.println("配置文件未找到，使用默认路径 products.dat");
            dataFilePath = "products.dat";
        } catch (IOException e) {
            System.out.println("配置文件读取失败，使用默认路径 products.dat");
            dataFilePath = "products.dat";
        }
    }

    // 保存商品数据到文件
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(dataFilePath))) {
            oos.writeObject(new ArrayList<>(productData.values()));
            System.out.println("商品数据已保存到 " + dataFilePath);
        } catch (IOException e) {
            System.out.println("保存数据失败: " + e.getMessage());
        }
    }

    // 从文件加载商品数据
    private void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            // 初始化默认数据
            productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
            productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
            productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
            productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(dataFilePath))) {
            List<Product> products = (List<Product>) ois.readObject();
            productData.clear();
            for (Product p : products) {
                productData.put(p.getId(), p);
            }
            System.out.println("已从 " + dataFilePath + " 加载 " + products.size() + " 条商品数据");
        } catch (FileNotFoundException e) {
            System.out.println("数据文件未找到，初始化默认数据");
            initDefaultData();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据失败，初始化默认数据: " + e.getMessage());
            initDefaultData();
        }
    }

    // 初始化默认数据（加载失败时调用）
    private void initDefaultData() {
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }

    // 备份数据方法（供ConsoleShop调用）
    public void backupData() {
        File source = new File(dataFilePath);
        File target = new File(dataFilePath + ".bak");
        if (!source.exists()) {
            System.out.println("源数据文件不存在，备份失败");
            return;
        }

        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(target)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("数据已备份到 " + target.getAbsolutePath());
        } catch (IOException e) {
            System.out.println("备份数据失败: " + e.getMessage());
        }
    }
}